from django.shortcuts import render
from django.http import JsonResponse,QueryDict,HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.forms.models import model_to_dict
import json,re,random,io,sys,requests,time,base64,os,uuid
from .models import MapboxImage
# Create your views here.

# 前端：【mapbox-diatomdaomap.com】
@csrf_exempt
def mapbox_addImage(request):
    try:
        requestData = json.loads(request.body)
        if requestData is None:
            return JsonResponse({"status": "error", "success": False,'data':'请正确传入参数'})

        location = requestData['location']
        countryCode = requestData['countryCode']
        lat = requestData['lat']
        lng = requestData['lng']
        image = requestData['image']
        # base64转图片存储
        imgdata = base64.b64decode(image.split(',')[1])
        _id = uuid.uuid1()
        file = open(r'E:\mapbox\mapbox-examples\mapbox-diatomdaomap.com\cards/'+str(_id) +'.png', 'wb')
        file.write(imgdata)
        file.close()

        # 存数据库
        mapboxImage = MapboxImage(location=location,countryCode=countryCode,lng=lng,lat=lat,uuid=_id)
        mapboxImage.save()

        return JsonResponse({"status": "ok", "success": True,'data':_id})

    except Exception as ex:
        print(ex)
        return JsonResponse({"status": "error", "success": False})

@csrf_exempt
def mapbox_getAll(request):
    try:
        mapboxs = MapboxImage.objects.all()
        features = []
        for mapbox in mapboxs:
            feature = {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        str(mapbox.lng),
                        str(mapbox.lat)
                    ]
                },
                "properties": {
                    "location": mapbox.location,
                    "country_code": mapbox.countryCode,
                    "card_image": mapbox.uuid
                }
            }
            features.append(feature)
        return JsonResponse({"status": "ok", "success": True,'data':{
            "type": "FeatureCollection",
            "features":features
        }})
    except Exception as ex:
        print(ex)
        return JsonResponse({"status": "error", "success": False})

@csrf_exempt
def mapbox_deleteCard(request):
    try:
        requestData = json.loads(request.body)
        if requestData is None:
            return JsonResponse({"status": "error", "success": False,'data':'请正确传入参数'})

        uuid = requestData['uuid']
        print(uuid)
        # 删除数据库
        MapboxImage.objects.filter(uuid=uuid).delete()
        # 删除文件
        path = r'E:\mapbox\mapbox-examples\mapbox-diatomdaomap.com\cards/'+uuid +'.png'
        if os.path.exists(path):  # 如果文件存在
            # 删除文件，可使用以下两种方法。
            os.remove(path)
        return JsonResponse({"status": "ok", "success": True})
    except Exception as ex:
        print(ex)
        return JsonResponse({"status": "error", "success": False})

# end
#=============================================

